<?php

namespace app\web\controller;
use app\web\model\OrderModel;
use app\common\controller\StoreBaseController;
use think\Db;
/**
 * 订单列表
 */
class OrderController extends StoreBaseController
{
 	 protected $model;
	
    protected function _initialize() {
        parent::_initialize();
        $this->model = new OrderModel();
    }
	    /**
     * 订单列表
     * @author [longx] 
     */
    public function index(){
		$field='m.*,g.goods_name,g.thumb,g.goods_lanmu,d.nick_name';
		$status = request()->param('status');//获取订单状态
		$where['m.agent_id'] = session('storeInfo')['id'];
		if($status != 0){
			$where['m.order_state'] = $status;
		}	
		if(request()->isPost()){
			$param = input('post.');
			//订单号
			if($param['order_number']){
				$where['m.sn'] = ['like', '%'.$param['order_number'].'%'];
			}
			//下单时间
			if($param['start_time']&&$param['end_time']){
				$where['m.order_time'] = ['between time', [$param['start_time'],$param['end_time']]];
			}
			//收货人姓名
			if($param['receiver']){
				$map['m.receiver'] = ['like', '%'.$param['receiver'].'%'];
			}
			//收货人号码
			if($param['receiver_mobile']){
				$map['m.receiver_mobile'] = ['like', '%'.$param['receiver_mobile'].'%'];
			}
			if($param['express_type']){
				$where['m.express_type'] = $param['express_type'];
			}
		}
	    $list = Db::name('mall_order')->alias('m')
	    ->field($field)
	    ->join('__MALL_ORDER_ITEM__ g','g.order_id=m.id','LEFT')
	    ->join('__MEMBER__ d','d.id=m.user_id','LEFT')
		->where($where)
		->order("m.order_time desc")
	    ->paginate(10);
		
		$list1=array();
		if($list){
			foreach($list as $k=>$v){
				$list1[$v['id']]=$v;
			}

			$order_ids = array_keys($list1);
						
			if($order_ids){
				$order_items = db("mall_order_item")->where("order_id","in",$order_ids)->select();
				foreach($order_items as $k1=>$v1){
					$p=Db::name('member')->where('id',$v1['user_id'])->find();
					$v1['username']=$p['real_name'];
					 $list1[$v1['order_id']]['items'][]=$v1;
				}
			}
		}
		$express = getListSiteBname("logistics");
		$this->assign("express",$express);
		$this->assign("list1",$list1);
	    return $this->fetch('index', ['list' => $list,'status'=>$status]);   
    }
   
    /**
     * [export导出]
     * @author [longx] 
     */
    public function export(){
 		$field='m.*,g.goods_name,g.thumb,g.goods_lanmu,d.nick_name';
		$status = request()->param('status');//获取订单状态
		$express_type = request()->param('express_type');//获取订单类型
		$where['m.express_type'] = $express_type;
		$where['m.agent_id'] = session('storeInfo')['id'];
		if($status != 0){
			$where['m.order_state'] = $status;
		}	
		if(request()->isPost()){
			$param = input('post.');
			//订单号
			if($param['order_number']){
				$where['m.sn'] = ['like', '%'.$param['order_number'].'%'];
			}
			//下单时间
			if($param['start_time']&&$param['end_time']){
				$where['m.order_time'] = ['between time', [$param['start_time'],$param['end_time']]];
			}
			//收货人姓名
			if($param['receiver']){
				$map['m.receiver'] = ['like', '%'.$param['receiver'].'%'];
			}
			//收货人号码
			if($param['receiver_mobile']){
				$map['m.receiver_mobile'] = ['like', '%'.$param['receiver_mobile'].'%'];
			}
		}
	    $list = Db::name('mall_order')->alias('m')
	    ->field($field)
	    ->join('__MALL_ORDER_ITEM__ g','g.order_id=m.id','LEFT')
	    ->join('__MEMBER__ d','d.id=m.user_id','LEFT')
		->where($where)
		->order("m.order_time desc")
	    ->paginate(100);
		
		$list1 = array();
		if($list){
			foreach($list as $k=>$v){
				$list1[$v['id']]=$v;
			}

			$order_ids = array_keys($list1);
						
			if($order_ids){
				$order_items = db("mall_order_item")->where("order_id","in",$order_ids)->select();
				foreach($order_items as $k1=>$v1){
					 $list1[$v1['order_id']]['items'][]=$v1;
				}
			}
		}
        $str = "商品,单价/数量,栏目,用户支付,买家,下单时间,订单状态,实付金额,\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list1 as $k=>$row){
        	foreach($row['items'] as $f=>$frow){
            $goods_name = iconv('utf-8','gbk',$frow['goods_name']); //中文转码 			
			$price = iconv('utf-8','gbk',$frow['price'].'/'.$frow['number'].'(件)');
			$add_time = iconv('utf-8','gbk',$frow['add_time']);			 
			$lanmu = $row['goods_lanmu'];
			if($lanmu == 1){
				$lanmuname = '疯狂抢';
			}else if($lanmu == 2){
				$lanmuname = '优惠购';
			}else if($lanmu == 3){
				$lanmuname = '赚积分';
			}else if($lanmu == 4){
				$lanmuname = '云拼团';
			}			                                     
            $goods_lanmu = iconv('utf-8','gbk',$lanmuname);                 
            $total_price = iconv('utf-8','gbk',$frow['total_price']);
			$nick_name = iconv('utf-8','gbk',$row['nick_name']);
			$order_state = $row['order_state'];
			if($order_state == 1){
				$statename = '待付款';
			}else if($order_state == 2){
				$statename = '拼团中';
			}else if($order_state == 3){
				$statename = '待发货';
			}else if($order_state == 4){
				$statename = '已发货';
			}else if($order_state == 5){
				$statename = '已完成';
			}else if($order_state == 6){
				$statename = '已关闭';
			}	  
			$order_state = iconv('utf-8','gbk',$statename);  
			$pay_price = iconv('utf-8','gbk',$row['pay_price']);                   
            $str .= $goods_name.",".$price.",".$goods_lanmu.",".$total_price.",".
            $nick_name.",".$add_time.",".$order_state.",".$pay_price.","."\n"; //用引文逗号分开 
            }
        } 
      
	  	if($express_type == 1){
	  		$filename ='快递订单列表.csv';   //设置文件名  
	  	}else{
	  		$filename ='O2O订单列表.csv';
	  	}
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
     }
   
   	
	/**
	 * 获取订单信息
	 */
	public function getOrderInfo(){
		$order=db("mall_order")->where('id', input("order_id"))->find();
		if($order){
			$code=200;
		}else{
			$code=406;
		}
		return json(['code'=>$code,'order'=>$order]);
	}
	/**
	 * 发货
	 */
	public function fahuo(){
		$data['delivery_time']=now_time();
		$data['express']=input('express');
		$data['express_no']=input('express_no');
		$data['order_state']=4;
		$res=db('mall_order')->where('sn',trim(input('sn')))->update($data);
		if($res){
			return json(['code'=>200,'msg'=>'发货成功']);
		}else{
			return json(['code'=>408,'msg'=>'发货失败']);
		}
	}

    /**
     * 
     *添加
     * @author [longx] 
     */
    public function add()
    {
        if(request()->isAjax()){
        	$param=input('post.');
			if ($this->model->allowField(true)->save($param) !== false) {
                    $this->success('添加成功', url('Order/index'));
            } else {
                $this->error('添加失败');
            }
        }
        return $this->fetch();
    }


    /**
     * [edit 编辑]
     * @return [type] [description]
     * @author [longx]
     */
    public function edit($id)
    {
        if(request()->isAjax()){
            $param = input('post.');         
         	if ($this->model->allowField(true)->save($param,$id) !== false) {
                    $this->success('修改成功', url('Order/index'));
            } else {
                $this->error('修改失败');
            }
        }
        $id = input('param.id');
        $this->assign('ad',$this->model->find($id));
        return $this->fetch();
    }



    /**
     * [del删除]
     * @author [longx] 
     */
    public function delete()
    {
        $id = input('param.id');
        if ($this->model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}